Title: How to Create a Custom Bulk Action

Publish Date: Sun, 15 Jan 2017 08:00:00 +0000

Categories: Uncategorized

Content:

[ablank href="https://wordpress.org/news/2016/12/vaughan/"]WordPress 4.7[/ablank] introduced a way to create your own [ablank href="https://make.wordpress.org/core/2016/10/04/custom-bulk-actions/"]custom bulk actions[/ablank] for your post types.

Before that, there were plugins to do it, but now that it’s in the core, it’s way easier to add a new bulk action, potentially you only need three functions!

Let’s see an example together about how to add a Move to Drafts bulk action, I know that is already possible if you bulk edit posts, but it involves many clicks, while with a bulk action is only a couple clicks!



Open the file functions.php in wp-content/themes/your-child-theme-name/ and add this code at the end of it:

https://gist.github.com/SiR-DanieL/747b91edbd5842ab2b82461640249599

This code adds a new item in the Bulk Actions dropdown in the posts list. It does nothing yet.

After it, add this code:

https://gist.github.com/SiR-DanieL/06246065be487e3c7085ce5d8615beef

This function handles instead the behaviour of your custom bulk action. In this case we first make sure that the action we are running is the custom one, not another. Then we cycle through the posts and we update their status.

In the end, we redirect back adding the total count of posts we edited in the URL.

The last part of the code is the following, which simply adds a notice that shows how many posts have been affected:

https://gist.github.com/SiR-DanieL/0ad6ac0dc4a5a285dff8cdc946ae1f41

Now you know how to add custom bulk actions, what will you use them for?
